<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="regist">
        <div>账号：<input type="text" name="username" class="name"></div>
        <div>账号：<input type="password" name="username" class="pwd"></div>
        <button>登录</button>
        <!-- 显示提示 -->
        <h1></h1>
    </form>

    <script>
        $("button").click((e) => {
            e.preventDefault(); // 阻止默认form传递数据行为
            let uname = document.querySelector(".name");
            let upwd = document.querySelector(".pwd");
            // 1
            let xhr = new XMLHttpRequest(); // 实例化对象
            // 2
            xhr.onreadystatechange = () => {
                if (xhr.status == 200 && xhr.readyState == 4) {
                    const h1 = document.querySelector("h1");
                    let res = JSON.parse(xhr.responseText);
                    // 判断返回的状态码
                    switch (res.status) {
                        case 0:
                            // 登录错误
                            h1.style.display = "block";
                            h1.innerText = res.msg; // 返回服务器错误提示
                            break;
                        case 1:
                            // 登录正确
                            h1.innerText = "";
                            h1.style.display = "none";
                            // 在本地登录成功后，返回的用户基本信息
                            localStorage.setItem("userinfo", JSON.stringify(res.userInfo));
                            location.href = "./index.html";
                            break;

                        default:
                            break;
                    }
                }
            };
            // 3
            xhr.open("POST", "/regist");
            // 原生ajax需要设置请求头  请求头放在open后 
            xhr.setRequestHeader(
                "content-type",
                "application/x-www-form-urlencoded",
            );
            // 4 显示数据
            xhr.send(`username=${uname.value}&password=${upwd.value}`);
        });
    </script>
</body>
</html>